const express = require('express');
const router = express.Router();
const StudyNote = require('../models/StudyNote');
const auth = require('../middleware/auth');

// Get user's study notes
router.get('/', auth, async (req, res) => {
  try {
    const notes = await StudyNote.find({ userId: req.user._id })
      .populate('sheetMusicId', 'title')
      .sort({ updatedAt: -1 });
    res.json(notes);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});

// Get single study note
router.get('/:id', auth, async (req, res) => {
  try {
    const note = await StudyNote.findById(req.params.id)
      .populate('sheetMusicId', 'title');
    
    if (!note) {
      return res.status(404).json({ message: 'Study note not found' });
    }
    
    if (note.userId.toString() !== req.user._id.toString()) {
      return res.status(403).json({ message: 'Not authorized' });
    }
    
    res.json(note);
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});

// Create new study note
router.post('/', auth, async (req, res) => {
  const note = new StudyNote({
    title: req.body.title,
    content: req.body.content,
    userId: req.user._id,
    sheetMusicId: req.body.sheetMusicId
  });

  try {
    const newNote = await note.save();
    res.status(201).json(newNote);
  } catch (error) {
    res.status(400).json({ message: error.message });
  }
});

// Update study note
router.patch('/:id', auth, async (req, res) => {
  try {
    const note = await StudyNote.findById(req.params.id);
    
    if (!note) {
      return res.status(404).json({ message: 'Study note not found' });
    }
    
    if (note.userId.toString() !== req.user._id.toString()) {
      return res.status(403).json({ message: 'Not authorized' });
    }
    
    Object.assign(note, req.body);
    const updatedNote = await note.save();
    res.json(updatedNote);
  } catch (error) {
    res.status(400).json({ message: error.message });
  }
});

// Delete study note
router.delete('/:id', auth, async (req, res) => {
  try {
    const note = await StudyNote.findById(req.params.id);
    
    if (!note) {
      return res.status(404).json({ message: 'Study note not found' });
    }
    
    if (note.userId.toString() !== req.user._id.toString()) {
      return res.status(403).json({ message: 'Not authorized' });
    }
    
    await note.remove();
    res.json({ message: 'Study note deleted' });
  } catch (error) {
    res.status(500).json({ message: error.message });
  }
});

module.exports = router; 